
package com.platform.modules.mall.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.Constant;
import com.platform.common.utils.Query;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.dao.MallOrderDao;
import com.platform.modules.mall.dao.MallShippingDao;
import com.platform.modules.mall.entity.MallOrderEntity;
import com.platform.modules.mall.entity.MallShippingEntity;
import com.platform.modules.mall.service.MallOrderService;
import com.platform.modules.mall.service.WxSendMsgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单表Service实现类
 *
 * @author
 * @date 2019-07-05 19:29:18
 */
@Service("mallOrderService")
public class MallOrderServiceImpl extends ServiceImpl<MallOrderDao, MallOrderEntity> implements MallOrderService {
    @Autowired
    private MallShippingDao shippingDao;
    @Autowired
    private WxSendMsgService sendMsgService;

    @Override
    public List<MallOrderEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page<MallOrderEntity> queryPage(Map<String, Object> params) {
        // 排序
        params.put("sidx", "T.ADD_TIME");
        params.put("asc", false);
        Page<MallOrderEntity> page = new Query<MallOrderEntity>(params).getPage();
        return page.setRecords(baseMapper.selectMallOrderPage(page, params));
    }

    @Override
    public boolean add(MallOrderEntity mallOrder) {
        return this.save(mallOrder);
    }

    @Override
    public boolean update(MallOrderEntity mallOrder) {
        return this.updateById(mallOrder);
    }

    @Override
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(String[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public boolean sendGoods(MallOrderEntity orderEntity) {
        MallOrderEntity order = baseMapper.selectById(orderEntity.getId());
        if (Constant.SHOPS_ORDER.equals(order.getOrderType())) {
            throw new BusinessException("自取订单无需发货！");
        }

        //付款状态
        Integer payStatus = order.getPayStatus();
        if (!Constant.PayStatus.YFK.getValue().equals(payStatus)) {
            throw new BusinessException("此订单未付款！");
        }

        MallShippingEntity shippingEntity = shippingDao.selectById(orderEntity.getShippingId());
        if (null != shippingEntity) {
            order.setShippingName(shippingEntity.getName());
            order.setShippingCode(shippingEntity.getCode());
        }
        order.setShippingId(orderEntity.getShippingId());
        order.setShippingNo(orderEntity.getShippingNo());
        order.setPostalCode(orderEntity.getPostalCode());
        //订单已发货
        order.setConfirmTime(new Date());
        order.setOrderStatus(Constant.OrderStatus.YFH.getValue());
        //已发货
        order.setShippingStatus(Constant.ShippingStatus.YFH.getValue());
        update(order);

        //发货通知
        return sendMsgService.notifyPaySuccess(order, Constant.STR_FIVE);
    }

    @Override
    public void statusChange(String id, Integer status,String userId) {
        MallOrderEntity orderEntity = this.lambdaQuery()
                .select(MallOrderEntity::getOrderStatus,MallOrderEntity::getUserId)
                .eq(MallOrderEntity::getId,id).one();
        if(orderEntity == null){
            throw new BusinessException("订单信息有误！ 请联系管理员");
        }
        if(StringUtils.isNotBlank(userId) && !userId.equals(orderEntity.getUserId())){
            throw new BusinessException("无权操作");
        }
        orderEntity.setId(id);
        switch (status){
            case 401:
                if(!orderEntity.getOrderStatus().equals(Constant.OrderStatus.YFK.getValue())){
                    throw new BusinessException("当前状态无法变更");
                }
                orderEntity.setShippingStatus(Constant.ShippingStatus.TH.getValue());
                orderEntity.setPayStatus(Constant.PayStatus.TK.getValue());
                break;
            case 301:
                if(!orderEntity.getOrderStatus().equals(Constant.OrderStatus.TKSH.getValue())){
                    throw new BusinessException("当前状态无法变更");
                }
                orderEntity.setShippingStatus(Constant.ShippingStatus.YFH.getValue());
                break;
            case 402:
                if(!orderEntity.getOrderStatus().equals(Constant.OrderStatus.TKSH.getValue())){
                    throw new BusinessException("当前状态无法变更");
                }
                orderEntity.setShippingStatus(Constant.ShippingStatus.TH.getValue());
                break;
            case 403:
                if(!orderEntity.getOrderStatus().equals(Constant.OrderStatus.QRSH.getValue())){
                    throw new BusinessException("当前状态无法变更");
                }
                break;
            default:
                throw new BusinessException("未知状态！");
        }
        orderEntity.setOrderStatus(status);
        this.update(orderEntity);
    }

    @Override
    public boolean confirmReceive(String id) {
        MallOrderEntity orderEntity = baseMapper.selectById(id);
        //发货状态
        Integer shippingStatus = orderEntity.getShippingStatus();
        //付款状态
        Integer payStatus = orderEntity.getPayStatus();
        if (!Constant.PayStatus.YFK.getValue().equals(payStatus)) {
            throw new BusinessException("此订单未付款，不能确认收货！");
        }
        if (!Constant.ShippingStatus.YFH.getValue().equals(shippingStatus)) {
            throw new BusinessException("此订单未发货或正在退货，不能确认收货！");
        }
        orderEntity.setShippingStatus(Constant.ShippingStatus.YSH.getValue());
        orderEntity.setOrderStatus(Constant.OrderStatus.QRSH.getValue());
        return update(orderEntity);
    }

    @Override
    public Map<String, Object> queryUserCountMap(Map<String, Object> params) {
        return baseMapper.queryUserCountMap(params);
    }

    @Override
    public MallOrderEntity queryById(String orderId) {

        return baseMapper.queryById(orderId);
    }

    @Override
    public List<MallOrderEntity> export(Map<String, Object> params) {
        return baseMapper.export(params);
    }

    @Override
    public List<MallOrderEntity> exportByCard(Map<String, Object> params) {
        return baseMapper.exportByCard(params);
    }

    @Override
    public Page<MallOrderEntity> selectLimit(Map<String, Object> params) {

        List<MallOrderEntity> list = baseMapper.selectLimit(params);

        Page<MallOrderEntity> page =new Page<>();
        page.setRecords(list);
        return page;
    }


    /**
     * 所有有效的订单才算订单数
     * @param userId
     * @param goodsId
     * @param maxNum
     * @return
     */
    @Override
    public boolean goodsQuatoVerify(String userId, String goodsId, Integer maxNum) {
        int size = this.lambdaQuery()
                .eq(MallOrderEntity::getUserId, userId)
                .eq(MallOrderEntity::getGoodsId, goodsId)
                .ne(MallOrderEntity::getPayStatus,4)//非退款订单
                /*100:订单超时已过期 101:订单已取消 102:订单已删除  401:没有发货，退款　402:已收货，退款退货 501:供应商退款 这些为无效订单*/
                .notIn(MallOrderEntity::getOrderStatus,100,101,102,401,402,501)
                .list().size();
        return maxNum>size;
    }
}
